package com.my.vote.pst.info;

import android.text.TextUtils;

import com.my.vote.VoteApplication;
import com.my.vote.entity.EUser;
import com.my.vote.entity.EVoteInfo;
import com.my.vote.entity.EVoteItem;
import com.my.vote.entity.req.ReqSignUp;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 功能描述:
 *
 * @author
 * @date 2018/4/14
 */
public class PstSigUp extends AbstractPresenter<IPstSigUp.IVSigUp> implements IPstSigUp {
    @Override
    public void sigup(final ReqSignUp req) {

        if (TextUtils.isEmpty(req.getTitle())) {
            getView().showToast("Please enter the title");
            return;
        }
        if (TextUtils.isEmpty(req.getDesc())) {
            getView().showToast("Please enter a brief introduction");
            return;
        }
        getView().showLoading(false);

        BmobQuery<EVoteInfo> query = new BmobQuery<>();
        query.getObject(AppCacheManager.getApplication(), req.getVoteId(), new GetListener<EVoteInfo>() {
            @Override
            public void onSuccess(final EVoteInfo voteInfo) {
                int candidateSize = voteInfo.getCandidateSize();
                voteInfo.setCandidateSize(candidateSize + 1);
                voteInfo.update(AppCacheManager.getApplication());

                EVoteItem voteItem = new EVoteItem();
                voteItem.setVoteId(voteInfo.getObjectId());
                final EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
                voteItem.setCreateUserId(user.getObjectId());

                voteItem.setVoteSize(0);
                voteItem.setSerialNumber(candidateSize + 1);
                voteItem.setIntroduce(req.getDesc());
                voteItem.setTitle(req.getTitle());

                voteItem.save(AppCacheManager.getApplication(), new SaveListener() {
                    @Override
                    public void onSuccess() {
                        getView().hideLoading();
                        getView().onSigUpSuccess();
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        getView().hideLoading();
                        getView().showToast("SigUp Vote Fail!");
                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {
                getView().hideLoading();
                getView().showToast("SigUp Vote Fail!");
            }
        });


    }


}
